package cn.eastseven.demo.chat;

import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.stereotype.Component;

import cn.eastseven.demo.netty.common.Header;
import cn.eastseven.demo.netty.common.MessageType;
import cn.eastseven.demo.netty.common.NettyMessage;

@Component
@Sharable
public class LoginAuthRespHandler extends ChannelHandlerAdapter {
	
	private Map<String, Boolean> nodeCheck = new ConcurrentHashMap<String, Boolean>();
	
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		System.out.println("channelRead: "+msg);
		NettyMessage message = (NettyMessage) msg;
		if(message.getHeader() != null && message.getHeader().getType() == MessageType.LOGIN_REQ) {
			String nodeIndex = ctx.channel().remoteAddress().toString();
			NettyMessage loginResponse = buildLoginResponse();
			if(nodeCheck.containsKey(nodeIndex)) {
				loginResponse.getHeader().setType(MessageType.LOGINED);
			} else {
				nodeCheck.put(nodeIndex, Boolean.TRUE);
			}
			
			System.out.println("channelRead: loginResponse="+loginResponse+", nodeCheck="+nodeCheck);
			ctx.writeAndFlush(loginResponse);
		} else {
			ctx.fireChannelRead(msg);
		}
	}
	
	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		ctx.flush();
	}
	
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		ctx.close();
		ctx.fireExceptionCaught(cause);
	}
	
	private NettyMessage buildLoginResponse() {
		NettyMessage loginResponse = new NettyMessage();
		Header header = new Header();
		header.setType(MessageType.LOGIN_RESP);
		loginResponse.setHeader(header);
		return loginResponse;
	}
}
